#!/usr/bin/env node

const fs       = require('fs'),
      start    = process.argv[2],
      filename = process.argv[3],
      join     = require('path').join,
      dirname  = './sysFile';


if(start == '-list'){
  try {

    const arr = fs.readdirSync(dirname);
    var brr = [];
    var j = 0;
    for(var i = 0; i < arr.length; i++){
      let path0 = dirname + '/' + arr[i];

      if(fs.statSync(path0).isFile() === true){
        brr[j] = arr[i];    
        j++;
      }     
    }

    var messages = [];
    for(var k = 0; k < brr.length; k++){
      let path1 = dirname + '/' + brr[k];
      var msg = {
        'filename': brr[k],
        'filesize': fs.statSync(path1).size
      };
      messages.push(msg);
    }

    function sortSize(a,b){
      return a.filesize - b.filesize;                        
    }

    messages.sort(sortSize); 
    console.log(messages);

  } catch(err) {
    console.error(err.message);
    console.log('信息有误');
    process.exit(1);
  }
}


if(start == '-show'){
  try{
    let path1 = dirname + '/' + filename;
    console.log(fs.readFileSync(path1).toString('utf8'));
  } catch(err) {
    console.error(err.message);
    console.log('该文件不存在');
    process.exit(2);
  }
}



if(start == '-del'){
  let src = dirname + '/' + filename;

  if(typeof(src) === 'undefined') {
    console.error('请指定要删除的文件名或者目录名！');
    process.exit(1);
  }

  if(!fs.existsSync(src)) {
    console.error('%s not exist!', src);
    process.exit(2);
  }


  if(fs.statSync(src).isFile()) { 
    fs.unlinkSync(src);
    console.log(filename+'文件删除成功');
  }
  else if(fs.statSync(src).isDirectory()){ 
    deleteDir(src);
    console.log(filename+'文件夹删除成功')
  }

  function deleteDir(folder) {
    let files = fs.readdirSync(folder);
    for(let i=0;i<files.length;i++) {
      let file = join(folder, files[i]);
      if(fs.statSync(file).isFile()) {
        fs.unlinkSync(file);
        continue;                                            
      }
      if(fs.statSync(file).isDirectory()) {
        deleteDir(file); 
      }                         
    }
    fs.rmdirSync(folder);
  }

}



  





